﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;

using CloudSoft.Workflows;

namespace ERPStore.Exporter.Workflows.Activities
{

	public sealed class GetPagedProductList : CodeActivity
	{
		public InArgument<int> PageIndex { get; set; }
		public InArgument<int> PageSize { get; set; }
		public OutArgument<List<ERPStore.Models.Product>> ProductList { get; set; }
		public OutArgument<int> ProductCountTotal { get; set; }
		public OutArgument<bool> NoMoreProduct { get; set; }

		protected override void Execute(CodeActivityContext context)
		{
			int pageIndex = context.GetValue(this.PageIndex);
			int pageSize = context.GetValue(this.PageSize);
			var catalogService = context.GetService<ERPStore.Services.ICatalogService>();
			var loggerService = context.GetService<ERPStore.Logging.ILogger>();

			var filter = new ERPStore.Models.ProductListFilter();
			int count = 0;
			IList<ERPStore.Models.Product> productList;
			int retryCount = 0;
			while (true)
			{
				try
				{
					productList = catalogService.GetProductListBySearch(filter, pageIndex, pageSize, out count);
					var progress = string.Format("process export products {0}/{1}", Math.Min(count, ((pageIndex + 1) * pageSize)), count);
					context.ReportProgress(count, pageIndex, pageSize, progress);
					loggerService.Info(progress);
					break;
				}
				catch (Exception ex)
				{
					if (retryCount > 5)
					{
						ex.Data.Add("RetryCount", "5 * 5s");
						throw(ex);
					}
					System.Threading.Thread.Sleep(5 * 1000);
					retryCount++;
				}
			}

			context.SetValue(ProductList, productList);
			context.SetValue(ProductCountTotal, count);
			context.SetValue(NoMoreProduct, productList.Count != 0);
		}
	}
}
